<template>
  <el-container>
    <!-- <RegionTree style="margin-top: 16px" @on-choose-region="filetrRegion" /> -->
    <el-main>
      <div class="default-main ba-table-box">
        <!-- 表格顶部菜单 -->
        <TableHeader
          :buttons="['refresh', 'comSearch', 'columnDisplay', 'back']"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 处理信息表单 -->
        <Handle v-model="state.showForm" :row-form="state.row" />
        <!-- 设备告警详情表单 -->
        <Info />
      </div> </el-main
  ></el-container>
</template>
<script lang="ts" setup>
import _ from "lodash";
import {
  ref,
  provide,
  onMounted,
  reactive,
  markRaw,
  onBeforeUnmount,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { EquipMWarn } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import TableHeader from "@/components/table/header/index.vue";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import Handle from "./popupForm.vue";
import { useRouter, useRoute, onBeforeRouteUpdate } from "vue-router";
// import RegionTree from "@/components/roleRegionTree/index.vue";
import Info from "./info.vue";
import { useRegion } from "@/store/backend/SysM/region";
import Cascader from "@/components/Cascader/index.vue";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor"; //实时设备监控仓库
import { useAccess } from "@/store/backend/DeviceM/access";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useWarnLog } from "@/store/backend/EquipM/warn";
import TagState from "@/components/dictTagState/index.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import { useNavTabs } from "@/store/navTabs";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const { proxy } = useCurrentInstance(); //全局事件总线
const region = useRegion();
const route = useRoute();
const router = useRouter();
const monitor = useBackendMonitor();
const access = useAccess();
const warnLog = useWarnLog();
const dictionary = useDictionary();
const navTabs = useNavTabs();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 字段显隐记忆功能 字段中有默认隐藏false情况的
const filedShowOffDefault = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(route.path + "/" + filter)
      ? true
      : false;
  }
  return "";
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + EquipMWarn)
      ? (navTabs as any).pageSizeMap.get(route.path + EquipMWarn)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(EquipMWarn), //this.api = api部门管理
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      // {
      //   label: "设备id",
      //   prop: "eqid",
      //   align: "center",
      //   operator: false,
      //   operatorPlaceholder: "模糊搜索",
      //   width: 70,
      // },
      {
        show: filedShowOff("ecode"),
        label: "设备编号",
        prop: "ecode",
        align: "center",
        operatorPlaceholder: "模糊搜索",
        operator: false,
      },
      {
        show: filedShowOff("pname"),
        label: "设备名称",
        prop: "pname",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("gatewaycode"),
        label: "网关编号",
        prop: "gatewaycode",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("cname"),
        label: "企业名称",
        prop: "cname",
        align: "center",
        operator: false,
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("username"),
        label: "维护人员",
        prop: "username",
        width: 80,
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("userPhone"),
        label: "维护人员联系方式",
        prop: "userPhone",
        align: "center",
        operator: false,
      },
      // {
      //   label: "所属区域",
      //   prop: "rname",
      //   align: "center",
      //   operator: false,
      //   operatorPlaceholder: "模糊搜索",
      // },
      {
        show: filedShowOff("state"),
        label: "告警状态",
        prop: "state",
        align: "center",
        // render: "tag",
        render: "customRender",
        customRender: markRaw(TagState),
        // custom: { 0: "danger", 1: "success" },
        operator: false,
        // replaceValue: {
        //   0: "未处理",
        //   1: "已处理",
        // },
      },
      {
        show: filedShowOff("reportName"),
        label: "告警原因",
        prop: "reportName",
        align: "center",
        operator: false,
      },
      // {
      //   label: "IP",
      //   prop: "ip",
      //   align: "center",
      //   operator: false,
      //   operatorPlaceholder: "模糊搜索",
      //   render: "tag",
      // },
      {
        show: filedShowOff("reportTime"),
        label: "告警时间",
        prop: "reportTime",
        align: "center",
        operator: false,
      },
      {
        show:
          filedShowOffDefault("regions") === ""
            ? false //默认false
            : filedShowOffDefault("regions"),
        label: "选择区域",
        prop: "regions",
        align: "center",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(Cascader),
      },
      {
        show: operatorShowOff([route.path + "/add", route.path + "/edit"]),
        label: "操作",
        align: "center",
        width: "140",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "handle", //与add绑定
            title: "处理",
            text: "",
            type: "primary",
            icon: "el-icon-Stamp",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
            // display: (row: TableRow, field: TableColumn) => {
            //   if (row.state) {
            //     return false;
            //   }
            //   return true;
            // },
          },
          {
            render: "tipButton",
            name: "info",
            title: "实况", //实况system:attribute:edit
            text: "",
            type: "primary",
            icon: "iconfont icon-XianShi",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "edit",
            title: "详情",
            text: "",
            type: "primary",
            icon: "iconfont icon-chaxunyujisuan",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: {
      regions: region.regionIds + "",
      eqid: route.query.eqid,
      pageSize: pageSizeKeep(),
    },
    acceptQuery: false,
  }
);
interface Region {
  address: string | null;
  addressDetail: string | null;
  areaFlag: string | null;
  areaId: number;
  areaName: string | null;
  areaNo: string | null;
  children: Region[];
  createBy: string | null;
  createTime: string | null;
  endTime: string | null;
  params: any;
  parentId: number;
  searchValue: string | null;
  startTime: string | null;
  updateBy: string | null;
  updateTime: string | null;
}
type RootObject = {
  equipid: number;
  name: string;
  avatar: string;
  owner_auth: number;
  user_auth: number;
  remark: string;
  is_online: number;
  is_alarm: number;
  is_running: number;
  status: number;
  last_parser_time: number;
  wind_speed: string;
  temperature: string;
  pa: string;
  carbonUse: string;
  dev_name: string;
  current_value_sensorid: number;
  current_value_updatetime: number;
  tags: any[];
  electric: string;
  voltage: string;
  address: string; //单个设备具体地址
  company_name: string; //隶属于公司或个人 名称
  parent_company_id: number; //相关联企业id
  company_address: string; //公司具体地址
  company_location: string; //公司经纬度
  contact: string; //代理人 可联系人名称或称呼
  te: string; //联系电话
};
// const filetrRegion = (row: Region, node: any) => {
//   //判断node属性中checkedNodes是否为空
//   if (node.checkedKeys.length == 0) {
//     //表示取消选择直接调用刷新表单方法
//     baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
//       regions: region.regionIds + "",
//     });
//     baTable.onTableHeaderAction("refresh", {});
//   } else {
//     baTable.comSearch.form.regions = node.checkedKeys + "";
//     baTable.getList(EquipMWarn);
//   }
// };

const state: { showForm: boolean; row: anyObj } = reactive({
  showForm: false,
  row: {},
});
//打开处理表单
const handleFormShow = (name: string, row: any) => {
  state.showForm = true; //打开表单
  state.row = row;
  console.log("row", row);
  warnLog.deviceItem = row;

  //查询单个设备详情
  // access.getDevicesItem(row.eqid).then((res: any) => {
  //   console.log("查询单个设备详情告警", res);
  // });
};
/** 点击查看详情按钮响应 */
const infoButtonClick = (row: TableRow) => {
  if (!row) return;
  // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
  let rowClone = _.cloneDeep(row);
  baTable.form.extend!["info"] = rowClone;
  baTable.form.operate = "info";
};
onBeforeRouteUpdate((to, form, next) => {
  console.log("当前路由啊,", route);
  next(false);
});
//查看 id暂为字符串
const monitorClick = (name: string, row: anyObj) => {
  // const infoButtonClick = (val: any) => {
  console.log("row", row);

  //从后台获取该设备数据跳转详情页
  monitor
    .getnowList({ eid: row.gatewaycode })
    .then((res) => {
      access
        .getDeviceByGateway(row.ecode, region.regionIds)
        .then((res: any) => {
          //处理coordinate坐标系
          res.rows[0].coordinate = JSON.parse(res.rows[0].coordinate);
          monitor.deviceData = res.rows[0];
          //为基本信息处理所属企业Map数据格式问题
          const business = useBusiness();
          const { companyList } = business;
          if (companyList.length === 0) {
            //为空就重新获取企业列表数据
            business.getCompanyList();
          }
        });
    })
    .catch((err) => {
      console.log(err);
    });
  router.push({
    path: "/admin/EquipM/Monitordetail",
    query: { eid: row.gatewaycode },
  });
};

proxy.eventBus.on("toMonitor", (row: any) => {
  //设备告警日志双击跳转设备详情页
  console.log("双击", row);
  access.getDevicesItem(row.eqid).then((res: any) => {
    console.log("获取单个设备信息", res);
    access.$patch((state) => {
      state.single = res.data;
    });
    router.push({
      path: "/admin/DeviceM/accessDetail",
      query: { eid: row.eqid },
    });
  });
});

//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("system_warning_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

// const nodes = () => {
//   let Nodes = JSON.parse(JSON.stringify(navTabs.state.authNodes));
//   console.log("Nodes", Nodes, "route", route.path);
//   operatorShowOff([route.path + "/add", route.path + "/edit"]);
// };
// nodes();
onMounted(() => {
  proxy.eventBus.emit("pointer"); //el-table显示双击小手套
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(EquipMWarn);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //点击打开处理表单
      if (data.name == "handle") {
        handleFormShow(data.name, data.row);
      } else if (data.name == "info") {
        monitorClick((data.row as TableRow)["id"], data.row as RootObject);
      } else {
        infoButtonClick(data.row);
      }
    }
  );
  proxy.eventBus.emit("clear");
});
onBeforeUnmount(() => {
  console.log("onBeforeUnmount");
  proxy.eventBus.emit("clear");
  proxy.eventBus.off("toMonitor");
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("warnStore", warnLog);
provide("accessStore", access);
provide("dictionary", dictionary);
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
.el-main {
  padding: 0;
}
</style>
